package com.example.exercise.common.mvc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    @Autowired
    private RateLimitInterceptor rateLimitInterceptor;
    @Autowired
    private RateLimitUserInterceptor rateLimitUserInterceptor;
    @Autowired
    private RateLimitApiInterceptor rateLimitApiInterceptor;

    /**
     * 添加拦截器，排出不拦截的静态资源，后面排除路径是swagger的路径，不用swagger时可以去掉
     * @param registry registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new RequestTimeConsumingInterceptor())
                .excludePathPatterns("/swagger**/**")
                .excludePathPatterns("/v3/api-docs/**")
                .excludePathPatterns("/v3/api-docs");
        registry.addInterceptor(rateLimitInterceptor)
                .excludePathPatterns("/swagger**/**")
                .excludePathPatterns("/v3/api-docs/**")
                .excludePathPatterns("/v3/api-docs");
        registry.addInterceptor(rateLimitUserInterceptor)
                .excludePathPatterns("/swagger**/**")
                .excludePathPatterns("/v3/api-docs/**")
                .excludePathPatterns("/v3/api-docs");
        registry.addInterceptor(rateLimitApiInterceptor)
                .excludePathPatterns("/swagger**/**")
                .excludePathPatterns("/v3/api-docs/**")
                .excludePathPatterns("/v3/api-docs");
    }

    /**
     * 添加可访问的静态资源，用swagger时才需要
     * @param registry registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
//        registry.addResourceHandler("swagger-ui.html")
//                .addResourceLocations("classpath:/static/")
//                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
//        // 配置 Swagger UI 资源路径
//        registry.addResourceHandler("/swagger-ui/index.html")
//                .addResourceLocations("classpath:/static/")
//                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        // 配置 knife4j UI静态资源
        registry.addResourceHandler("/doc.html")
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/META-INF/resources/");
    }

}
